package public

import (
	"emsctrl/pid"
	"emsctrl/util"
)

var G_Table RemoteAdjCtrlRegTable
var G_Current_Policy CurrentPolicy

type RemoteSignal struct {
	RunState               int `json:"run_state "`
	PcsRunState            int `json:"pcs_run_state"`
	PcsOpenState           int `json:"pcs_open_state "`
	PcsGridConnState       int `json:"pcs_grid_conn_state "`
	PcsRemoteState         int `json:"pcs_remote_state"`
	PcsFaultState          int `json:"pcs_fault_state "`
	PcsEmegstop            int `json:"pcs_emegstop"`
	PcsAlarmState          int `json:"pcs_alarm_state "`
	BMSFaultState          int `json:"bms_fault_state "`
	BMSAlarmState          int `json:"bms_alarm_state "`
	WaterOutState          int `json:"water_out_state "`
	SmogState              int `json:"smog_state "`
	AirconnFaultState      int `json:"airconn_fault_state "`
	ChargingState          int `json:"charging_state "`
	DisChargeState         int `json:"dis_charge_state "`
	PcsCommState           int `json:"pcs_comm_state "`
	BmsCommState           int `json:"bms_comm_state "`
	AirconnCommState       int `json:"airconn_comm_state "`
	WaterDevCommState      int `json:"water_dev_comm_state "`
	SmogDevCommState       int `json:"smog_dev_comm_state "`
	PvCommState            int `json:"pv_comm_state "`
	FireProteCommState     int `json:"fire_prote_comm_state "`
	ChargeStationCommState int `json:"charge_station_comm_state "`
	BmsUpVolState          int `json:"bms_up_vol_state "`
}

type RemoteMetering struct {
	Soc                   int32   `json:"soc "`
	StationActivePower    float32 `json:"station_active_power "`
	StationReactivePower  float32 `json:"station_reactive_power "`
	BmsActivePower        float32 `json:"bms_active_power"`
	BmsReactivePower      float32 `json:"bms_reactive_power"`
	GridActivePower       float32 `json:"grid_active_power "`
	GridReactivePower     float32 `json:"grid_reactive_power "`
	StationPositiveEnergy float32 `json:"station_positive_energy "`
	StationReverseEnergy  float32 `json:"station_reverse_energy "`
	GridPositiveEnergy    float32 `json:"grid_positive_energy "`
	GridReverseEnergy     float32 `json:"grid_reverse_energy "`
	EnvironTemper         float32 `json:"environ_temper "`
	EnvironHumidity       float32 `json:"environ_humidity "`
	CurMaxDemand          float32 `json:"cur_max_demand "`
	BmsAlarmLevel         int     `json:"bms_alarm_level "`
	PvActivePower         float32 `json:"pv_active_power "`
	ChargeStationPower    float32 `json:"charge_station_power "`
	LoadPower             float32 `json:"load_power "`
}

type RemoteCtrl struct {
	StationOpenCtrl        int     `json:"station_open_ctrl"`
	StationGridConnCtrl    int     `json:"station_grid_conn_ctrl"`
	AntiRefluxCtrl         int     `json:"anti_reflux_ctrl"`
	GridCapaCtrl           int     `json:"grid_capa_ctrl"`
	GridDemandCtrl         int     `json:"grid_demand_ctrl"`
	EnvironTemperProtect   float32 `json:"environ_temper_protect"`
	DODProtect             int     `json:"dod_protect"`
	SOCGridDisconnProtect  int     `json:"soc_grid_disconn_protect"`
	CellMaxVolProtect      int     `json:"cell_max_vol_protect"`
	CellMinxVolProtect     int     `json:"cell_minx_vol_protect"`
	PackMaxTemperProtect   int     `json:"pack_max_temper_protect"`
	PrimaryFreqModuleCtrl  int     `json:"primary_freq_module_ctrl"`
	ElectricityQualityCtrl int     `json:"electricity_quality_ctrl"`
	BmsUPVolCtrl           int     `json:"bms_up_vol_ctrl"`
}

type PIdAdjustPara struct {
	P float64 `json:"p"`
	I float64 `json:"i"`
	D float64 `json:"d"`
}

type ChargeDischargeType int32

const (
	POSTITIVE_TYPE ChargeDischargeType = 1
	NEGATIVE_TYPE  ChargeDischargeType = -1
)

type Power struct {
	ChargeDischargeMode ChargeDischargeType `json:"charge_discharge_mode"`
	ActionPower         float32             `json:"action_power"`
	ReactivePower       float32             `json:"reactive_power"`
}
type AirConn struct {
	RefrigerationTemp int32 `json:"refrigeration_temp"`
	CoolingReturnDiff int32 `json:"cooling_return_diff"`
	HeatingTemp       int32 `json:"heating_temp"`
	HeatReturnDiff    int32 `json:"heat_return_diff"`
}
type SocInfo struct {
	SocMax            int32 `json:"soc_max"`
	SocMin            int32 `json:"soc_min"`
	DisConnGridSocMin int32 `json:"dis_conn_grid_soc_min"`
}

type CellInfo struct {
	VolLower  float32 `json:"vol_lower"`
	VolHight  float32 `json:"vol_hight"`
	TempHight float32 `json:"temp_hight"`
}

type GeneratorInfo struct {
	VolHight    float32 `json:"vol_hight"`
	VolLower    float32 `json:"vol_lower"`
	FreqHight   float32 `json:"freq_hight"`
	FreqLower   float32 `json:"freq_lower"`
	ChDischStep float32 `json:"ch_disch_step"`
}

type ReactivePower struct {
	CapacitiveReactive float32 `json:"capacitive_reactive"`
	SensoryReactive    float32 `json:"sensory_reactive"`
}

type TransFormerInfo struct {
	Capacity float32 `json:"capacity"`
	Ratio    int     `json:"ratio"`
	Demond   int     `json:"demond"`
	PId      *pid.PID
}

type IncreaseCapaInfo struct {
	LoadChargeLow        float32 `json:"load_charge_low"`
	LoadDischargeLow     float32 `json:"load_discharge_low"`
	LoadDischargeRetDiff float32 `json:"load_discharge_ret_diff"`
	RetDiffPay           float32 `json:"ret_diff_pay"`
}

const (
	REMOTE_ADJ_MAX = 2
	TIME_LINE_MAX  = 2
)

type ChDisChTimeLine struct {
	Index      int
	Mode       int    `json:"mode"`
	StartTime  string `json:"start_time"`
	StartVal   int
	StopTime   string `json:"stop_time"`
	StopVal    int
	Power      float32 `json:"power"`
	Ratio      int     `json:"ratio"`
	TrackPower float32 `json:"track_power"`
}

type DateTime struct {
	StartDate string `json:"start_date"`
	EndDate   string `json:"end_date"`
	WeekDay   string `json:"week_day"`
}

type AntiReflux struct {
	Mode  int     `json:"mode"`
	Start float32 `json:"start"`
	End   float32 `json:"end"`
	PId   *pid.PID
}

type RemoteAdjustment struct {
	RunMode               int               `json:"run_mode"`
	PolicyMode            int               `json:"policy_mode"`
	ProxyMode             int               `json:"proxy_mode"`
	DemandMode            int               `json:"demand_mode"`
	AntiReflux            AntiReflux        `json:"anti_reflux"`
	LoadTrackMode         int               `json:"load_track_mode"`
	MaxDisChargePower     float32           `json:"max_dis_charge_power"`
	MaxChargePower        float32           `json:"max_charge_power"`
	MaxPvPower            float32           `json:"max_pv_power"`
	StationCapacity       int               `json:"station_capacity"`
	IncreaseCapaPara      IncreaseCapaInfo  `json:"increase_capa_para"`
	PIDPara               PIdAdjustPara     `json:"pid_para"`
	PowerPara             Power             `json:"power_para"`
	AirPara               AirConn           `json:"air_para"`
	UpperLimitEnvTemp     int32             `json:"upper_limit_env_temp"`
	SocPara               SocInfo           `json:"soc_para"`
	CellPara              CellInfo          `json:"cell_para"`
	GenerPara             GeneratorInfo     `json:"gener_para"`
	ReactivePara          ReactivePower     `json:"reactive_para"`
	PowerDistributionMode int               `json:"power_distribution_mode"`
	TransPara             TransFormerInfo   `json:"trans_para"`
	Date                  DateTime          `json:"data"`
	Priority              int               `json:"priority"`
	TimeLine              []ChDisChTimeLine `json:"time_line"`
}

type RemoteAdjCtrlRegTable struct {
	RemoteAdjCtrlTable []RemoteAdjRemoteCtrlMng `json:"remote_adj_ctrl_table"`
}

type RemoteAdjRemoteCtrlMng struct {
	RemoteAdj  RemoteAdjustment `json:"remote_adj"`
	RemoteCtrl RemoteCtrl       `json:"remote_ctrl"`
}

type CurrentPolicy struct {
	RemoteAdjRemoteCtrMng RemoteAdjRemoteCtrlMng
	RunModeSel            RunMode
	RemoteSignal          RemoteSignal
	RemoteMetering        RemoteMetering
	CurrTimeline          ChDisChTimeLine
	Cmd                   chan []byte
	DayUpgrade            int
}

func (Cp *CurrentPolicy) PidInit() {
	Cp.RemoteAdjRemoteCtrMng.RemoteAdj.AntiReflux.PId = &pid.PID{}
	Cp.RemoteAdjRemoteCtrMng.RemoteAdj.TransPara.PId = &pid.PID{}
	Cp.RemoteAdjRemoteCtrMng.RemoteAdj.AntiReflux.PId.Kp = Cp.RemoteAdjRemoteCtrMng.RemoteAdj.PIDPara.P
	Cp.RemoteAdjRemoteCtrMng.RemoteAdj.AntiReflux.PId.Ki = Cp.RemoteAdjRemoteCtrMng.RemoteAdj.PIDPara.I
	Cp.RemoteAdjRemoteCtrMng.RemoteAdj.AntiReflux.PId.Kd = Cp.RemoteAdjRemoteCtrMng.RemoteAdj.PIDPara.D
	Cp.RemoteAdjRemoteCtrMng.RemoteAdj.TransPara.PId.Kp = Cp.RemoteAdjRemoteCtrMng.RemoteAdj.PIDPara.P
	Cp.RemoteAdjRemoteCtrMng.RemoteAdj.TransPara.PId.Ki = Cp.RemoteAdjRemoteCtrMng.RemoteAdj.PIDPara.I
	Cp.RemoteAdjRemoteCtrMng.RemoteAdj.TransPara.PId.Kd = Cp.RemoteAdjRemoteCtrMng.RemoteAdj.PIDPara.D
}

func (Cp *CurrentPolicy) TimeLineUpgrade() {
	for i, line := range Cp.RemoteAdjRemoteCtrMng.RemoteAdj.TimeLine {
		//fmt.Println(i, line.StartVal, line.StopVal)
		second := util.CompareTimeSecond(line.StopVal, line.StartVal)
		if second == true {
			//fmt.Println(line.Power, line.TrackPower, line.Ratio, line.Mode)
			if Cp.CurrTimeline.Index != i {
				Cp.CurrTimeline = line
				Cp.CurrTimeline.Index = i
			}
		}
	}
}

func Get_Gtable() RemoteAdjCtrlRegTable {
	return RemoteAdjCtrlRegTable{}
}

func Get_Current_Polic() *CurrentPolicy {
	return &G_Current_Policy
}
